﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using PublicLib.Lib.Help;
using System.Net;
using PublicLib.Def;
using System.Diagnostics;
using System.Web;

namespace WebServerHntj
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“ControlInterface”。
    // 注意: 为了启动 WCF 测试客户端以测试此服务，请在解决方案资源管理器中选择 ControlInterface.svc 或 ControlInterface.svc.cs，然后开始调试。
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ControlInterface : IControlInterface
    {
        public Stream RequestData(string user, string operation, Stream data)
        {
            try
            {
                Debug.WriteLine(DateTime.Now.ToString() + " ControlInterface:RequestData");
                using (energybasedbEntities entity = new energybasedbEntities())
                {
                    string postString = String.Empty;
                    using (StreamReader sr = new StreamReader(data, PublicDef.PageEncoding))
                    {
                        postString = sr.ReadToEnd();
                    }
                    string stageString = String.Empty;
                    try
                    {
                        stageString = Newtonsoft.Json.Linq.JObject.Parse(postString)["stage"].ToString();
                    }
                    catch { }
                    var single = (from c in entity.operationtable where c.userid.Equals(user) && c.stage.Equals(stageString) select c).FirstOrDefault();

                    if (single != null)
                    {
                        if (CheckRunning(user,stageString).Length > 0)
                        {
                            single.operation = operation;
                            //single.userid = user;
                            single.data = postString;
                            single.stage = stageString;
                        }
                        else
                            single.data = "opera is running";
                    }
                    else
                    {
                        single = entity.operationtable.Create();
                        single.operation = operation;
                        single.userid = user;
                        single.data = postString;
                        single.stage = stageString;
                        entity.operationtable.Add(single);
                    }
                    entity.SaveChanges();
                }
                return "Send OK".ToStream();
            }
            catch (Exception ex)
            {
                return ex.Message.ToStream();
            }
        }
        public Stream CheckRunning(string user, string stage)
        {
            Debug.WriteLine(DateTime.Now.ToString() + " ControlInterface:CheckRunning");
            string res = "";
            try
            {
                using (energybasedbEntities entity = new energybasedbEntities())
                {
                    var single = (from c in entity.operationtable where c.userid.Equals(user) && c.stage.Equals(stage) select c).FirstOrDefault();

                    if (single != null && !string.IsNullOrWhiteSpace(single.data) && !single.operation.Equals(DataModel.PublicModel.Typedef.ErrorType.OK.ToString(), StringComparison.CurrentCultureIgnoreCase))
                    {
                        res = "busy";
                    }
                    else
                    {
                        res = string.Empty;
                    }
                }
                return res.ToStream();
            }
            catch (Exception ex)
            {
                return ex.Message.ToStream();
            }
        }
        public Stream CancelRunning(string user, Stream data)
        {
            Debug.WriteLine(DateTime.Now.ToString() + " ControlInterface:CancelRunning");
            string res = "Error";
            try
            {
                string postString = String.Empty;
                using (StreamReader sr = new StreamReader(data, PublicDef.PageEncoding))
                {
                    postString = sr.ReadToEnd();
                }
                string stageString = String.Empty;
                string password = String.Empty;
                try
                {
                    stageString = Newtonsoft.Json.Linq.JObject.Parse(postString)["stage"].ToString();
                    password = Newtonsoft.Json.Linq.JObject.Parse(postString)["password"].ToString();
                    //Debug.WriteLine(stageString + " " + password);
                }
                catch (Exception ex) { Debug.WriteLine(ex.ToString()); }
                if (!password.Equals("funyammy", StringComparison.CurrentCultureIgnoreCase))
                {
                    return null;
                }
                using (energybasedbEntities entity = new energybasedbEntities())
                {
                    var single = (from c in entity.operationtable where c.userid.Equals(user) && c.stage.Equals(stageString) select c).FirstOrDefault();
                    //Debug.WriteLine(single.userid + ":" + single.stage + ":" + single.data);
                    if (single != null && !string.IsNullOrWhiteSpace(single.data) && !single.operation.Equals(DataModel.PublicModel.Typedef.ErrorType.OK.ToString(), StringComparison.CurrentCultureIgnoreCase))
                    {
                        single.data = string.Empty;
                        single.operation = DataModel.PublicModel.Typedef.Operator.non.ToString();
                        entity.SaveChanges();
                        res = "OK";
                    }
                    else
                    {
                        res = "OK";
                    }
                }
                return res.ToStream();
            }
            catch (Exception ex)
            {
                return ex.Message.ToStream();
            }
        }
        public Stream ClearLog(string user, string password)
        {
            try
            {
                clearLogOperator(user, password, HttpContext.Current.Server.MapPath("~/ETLDebugError.html"));
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            return clearLogOperator(user, password, HttpContext.Current.Server.MapPath("~/DataServerDebugRecord.html"));
        }

        private static Stream clearLogOperator(string user, string password, string logPath)
        {
            if (user.Equals("funyammy") && password.Equals("funyammy"))
            {
                try
                {
                    System.IO.File.Delete(logPath);
                    var file = System.IO.File.Create(logPath);
                    StreamWriter sw = new StreamWriter(file,Encoding.Default);
                    sw.WriteLine("<head> <meta http-equiv=\"Content - Type\" content=\"text / html; charset = gb2312\"> </head>");
                    sw.WriteLine("<a href=\"RequestControl/ClearLog?user=funyammy&password=funyammy\" >清除历史纪录</a><br/>");
                    sw.Flush();
                    sw.Close();
                }
                catch (Exception ex)
                {
                    return ex.ToString().ToStream();
                }
                return "完成".ToStream();
            }
            else
            {
                return "用户名或密码错误？".ToStream();
            }
        }
    }
}
